package db

import event.InventoryChangedEvent
import ext.log
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject


class WaresCargo(val wares: Wares, val cargos: ArrayList<Cargo>) {

    fun toJson(): JSONObject {
        val json = JSONObject()
        json.put("wares", wares.toJson())
        val arr = JSONArray()
        for (cargo in cargos) {
            arr.put(cargo.toJson())
        }
        json.put("cargos", arr)
        return json
    }

    companion object {

        fun withWares(wares: Wares): WaresCargo {
            val id = wares.id
            val cargos = Cargo.queryByWaresId(id)
            val normals = ArrayList<Cargo>()
            for (cargo in cargos) {
                if (cargo.isNotOverdue()) {
                    normals.add(cargo)
                } else {
                    log("$cargo 过期")
                    cargo.delete()
                }
            }
            return WaresCargo(wares, normals)
        }
    }

    fun size() = cargos.size

    fun findNormalCargoAndDelete(): Cargo {
        val normals = ArrayList<Cargo>()
        /**
         * 取出所有没有过期的产品
         */
        for (cargo in cargos) {
            if (cargo.isNotOverdue()) {
                normals.add(cargo)
            }
        }
        /**
         * 所有的都过期了
         */
        if (normals.isEmpty()) {
            cargos.clear()
            Cargo.deleteByWaresId(wares.id)
            EventBus.getDefault().post(InventoryChangedEvent())
            throw Exception("该产品售罄或者全部过期")
        }
        /**
         * 取出最先放进去的产品
         */
        var min = Long.MAX_VALUE
        var normal: Cargo? = null
        for (i in 0 until normals.size) {
            if (normals[i].overdueTimestamp < min) {
                min = normals[i].overdueTimestamp
                normal = normals[i]
            }
        }
        cargos.remove(normal)
        normal!!.delete()
        EventBus.getDefault().post(InventoryChangedEvent())
        return normal!!
    }

    fun isAllOverdue(): Boolean {
        for (cargo in cargos) {
            if (cargo.isNotOverdue()) {
                return false
            }
        }
        cargos.clear()
        return true
    }

}
